#include "stm32f10x.h"                  // Device header

void PWM_Init(void)
{
	//RCC开启时钟：TIM GPIO
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
//	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	
	//配置GPIO：复用推挽输出
	GPIO_InitTypeDef led_gpio;
	led_gpio.GPIO_Mode = GPIO_Mode_AF_PP;
	led_gpio.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9;
	led_gpio.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &led_gpio);
	
//	/*
//	禁用JTAG 重映射定时器通道引脚GPIOA15
//	*/
//	GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
//	GPIO_PinRemapConfig(GPIO_FullRemap_TIM2,ENABLE);
	
	//配置时基单元
	TIM_InternalClockConfig(TIM2);//配置时钟模式：内部时钟
	TIM_TimeBaseInitTypeDef tim_timebaseinitstructure;//配置时基单元：PSC CNT ARR
	tim_timebaseinitstructure.TIM_ClockDivision = TIM_CKD_DIV1;
	tim_timebaseinitstructure.TIM_CounterMode = TIM_CounterMode_Up;
	tim_timebaseinitstructure.TIM_Period = 20000 - 1;		// ARR
	tim_timebaseinitstructure.TIM_Prescaler = 72 - 1;		//PSC
	tim_timebaseinitstructure.TIM_RepetitionCounter = 0;	//高级定时器用到的
	TIM_TimeBaseInit(TIM4,&tim_timebaseinitstructure);
	
	//配置输出比较单元：CCR 输出比较模式 极性选择 输出使能
	TIM_OCInitTypeDef tim_ocinitstructure;
	TIM_OCStructInit(&tim_ocinitstructure);		//全部赋初值，以免出错
	tim_ocinitstructure.TIM_OCMode = TIM_OCMode_PWM1;
	tim_ocinitstructure.TIM_OCPolarity = TIM_OCPolarity_High;
	tim_ocinitstructure.TIM_OutputState = TIM_OutputState_Enable;
	tim_ocinitstructure.TIM_Pulse = 0;			//CCR
	TIM_OC1Init(TIM4,&tim_ocinitstructure);	//通道1：控制舵机1	PA15
	TIM_OC2Init(TIM4,&tim_ocinitstructure);	//通道2：控制舵机2	PA1
	TIM_OC3Init(TIM4,&tim_ocinitstructure);	//通道3：控制舵机3	PA2
	TIM_OC4Init(TIM4,&tim_ocinitstructure);	//通道4：控制舵机4	PA3
	
	//启动定时器/计数器
	TIM_Cmd(TIM4, ENABLE);
}

//封装 设置CCR的值
void PWM_SetCompare1(uint16_t compare)
{
	TIM_SetCompare1(TIM4, compare);
}

void PWM_SetCompare2(uint16_t compare)
{
	TIM_SetCompare2(TIM4, compare);
}

void PWM_SetCompare3(uint16_t compare)
{
	TIM_SetCompare3(TIM4, compare);
}

void PWM_SetCompare4(uint16_t compare)
{
	TIM_SetCompare4(TIM4, compare);
}
